package es.ucm.fdi.pe.practica2.interfaz2;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

import es.ucm.fdi.pe.practica2.interfaz2.ConfigPanel.SimpleOption;

/**
 * An option that allows for file choices. 
 * @author Jose Luis Perez
 */	
public class ChoiceFileOption<T> extends SimpleOption<T> {
	private String ruta="";
	JTextField jtf = new JTextField("");
	public ChoiceFileOption(String label, String tooltip, String fieldName) {
		super(label, tooltip, fieldName);
		jtf.setSize(new Dimension(82,20));
		jtf.setMinimumSize(jtf.getSize());
		jtf.setMaximumSize(jtf.getSize());
		jtf.setPreferredSize(jtf.getSize());
		jtf.setEditable(false);
	}
	
	public ChoiceFileOption(String label, String tooltip) {
		this(label, tooltip, null);
	}
	
	@Override
	public JComponent getControlComponent() {
		JPanel p = new JPanel();
		
		JButton jb = new JButton("Abrir");
		p.add(jtf);
		p.add(jb);
		jb.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) { 
				JFileChooser chooser = new JFileChooser();
			    TXTFilter filter = new TXTFilter();
			    chooser.setFileFilter(filter);
			    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			    chooser.setCurrentDirectory(new File("./Ficheros"));
			    int returnVal = chooser.showOpenDialog(null);
			    if(returnVal == JFileChooser.APPROVE_OPTION)
			            ruta=chooser.getSelectedFile().getAbsolutePath();
			    jtf.setText(ruta);
			    jtf.setSize(new Dimension(82,20));
				cp.rootPanel.update(); 
			}
		});
		return p;
	}
	@Override
	protected Object readControl() {
		return ruta;
	}
	@Override
	protected boolean isValid(Object v) {
		return !ruta.equals("");
	}			
	@Override 
	protected void writeControl(Object v) {			
		ruta=(String) v;
		jtf.setText((String) v);
	}
}
